package com.ruoyi.quartz.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxMerchantOrder;
import com.ruoyi.business.service.IHcxAppUserService;
import com.ruoyi.business.service.IHcxMerchantOrderService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
@AllArgsConstructor
public class RyTask {

    private final IHcxMerchantOrderService merchantOrderService;

    private final RedisCache redisCache;

    private final IHcxAppUserService hcxAppUserService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        Console.log(StrUtil.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        Console.log("执行有参方法：" + params);
    }

    public void ryNoParams() {
        Console.log("执行无参方法");
    }


    /**
     * 自动取消超时未支付的订单
     */
    public void cancleOrder() {

        // 定时取消订单
        String orderValid = redisCache.getCacheObject(Constants.SYS_CONFIG_KEY + Constants.HCXORDERVALID);


        // 查询符合要求的
        List<HcxMerchantOrder> list = merchantOrderService.list(new LambdaQueryWrapper<HcxMerchantOrder>().eq(HcxMerchantOrder::getStatus, Constants.ZERO));
        List<HcxMerchantOrder> fuheList = list.stream().filter(hcxMerchantOrder -> DateUtil.between(hcxMerchantOrder.getCreateTime(), DateUtils.getNowDate(), DateUnit.MINUTE) > Long.valueOf(orderValid)).collect(Collectors.toList());
        for (HcxMerchantOrder hcxMerchantOrder : fuheList) {
            hcxMerchantOrder.setStatus(Constants.FOUR);
        }
        merchantOrderService.updateBatchById(fuheList);
    }


    /**
     * 定时检测vip会员的洗车卡次数是否用完 如果未用完则则检测会员卡是否到期
     */
    public void detectionExpiration () {
        List<HcxAppUser> hcxAppUsers = hcxAppUserService.list(new LambdaQueryWrapper<HcxAppUser>()
                .eq(HcxAppUser::getVipFlag, Constants.ONE)
                .ne(HcxAppUser::getVipTime,null)
                .apply(
                        "date_format(vip_time,'%y%m%d HH:mm:ss') >= date_format({0},'%y%m%d HH:mm:ss')",
                        new Date()));
        for (HcxAppUser hcxAppUser : hcxAppUsers) {
            hcxAppUser.setVipFlag(Constants.ZERO);
            hcxAppUser.setVipTime(new Date());
        }
        hcxAppUserService.updateBatchById(hcxAppUsers);
    }
}
